package com.hunan.api.catv.service.biz.system;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.CacheName;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.po.SystemDict;
import com.hunan.api.catv.entity.vo.SystemDictVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.impl.system.SystemDictService;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

@CacheConfig(cacheNames = CacheName.system)
@Service
public class SystemDictBiz extends ResultService {

    private static final String OPENABLE_SYSTEM_DIC_KEY = "OPENABLE_SYSTEM_DIC_KEY";

    @Autowired
    SystemDictService systemDictService;

    @Autowired
    SystemDictBiz systemDictBiz;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    CacheBiz cacheBiz;

    public PageInfo<SystemDictVo> page(int pageNum, int pageSize, String dictName) {
        PageHelper.startPage(pageNum, pageSize);
        SystemDict systemDict = new SystemDict();
        systemDict.setDictName(dictName);
        List<SystemDictVo> list = systemDictService.list(systemDict);
        return new PageInfo<SystemDictVo>(list);
    }

    public SystemDictVo info(String key) {
        SystemDict systemDict = new SystemDict();
        systemDict.setDictName(key);
        return systemDictService.get(systemDict);
    }

    public SystemDictVo info(Integer id) {
        return systemDictService.getById(id);
    }

    public ServiceResult add(SystemDict systemDict) {
        ServiceResult serviceResult = systemDictService.add(systemDict);
        if (serviceResult.getStatus()) {
            redisUtils.delObjectCacheInfo(CacheName.systemGetAll);
        }
        return serviceResult;
    }

    public ServiceResult edit(SystemDict systemDict) {
        if (ObjectUtils.isEmpty(systemDict.getSysDictId())) {
            return buildFail("", "id not null");
        }
        if (Constants.app_init_start.equals(systemDict.getDictName())) {
            JsonArray array = GsonUtils.fromJson(systemDict.getDictValue(), JsonArray.class);
            for (int i = 0; i < array.size(); i++) {
                JsonObject obj = array.get(i).getAsJsonObject();
                Integer type = obj.get("type").getAsInt();
                if (type == 1) {
                    JsonObject links = GsonUtils.fromJson(obj.get("links").getAsString(), JsonObject.class);
                    obj.addProperty("link", links.get("android").getAsString());
                }
                if (type == 2) {
                    obj.addProperty("link", obj.get("links").getAsString());
                }
            }
            systemDict.setDictValue(GsonUtils.toJson(array));
        }
        ServiceResult editResult = systemDictService.update(systemDict);
        if (!editResult.getStatus()) {
            return buildFail(ConstantsMsg.admin_edit_fail);
        }
        //缓存刷新
        if (editResult.getStatus()) {
            String systemByKey = MessageFormat.format(CacheName.systemByKey, systemDict.getDictName());
            String systemStringByKey = MessageFormat.format(CacheName.systemStringByKey, systemDict.getDictName());
            String beanNames = MessageFormat.format("apiDictCache?{0};systemDictCache?{1}", systemDict.getDictName(), systemDict.getDictName());
            cacheBiz.flushCacheInfo(beanNames, systemByKey, systemStringByKey, CacheName.systemGetAll);
        }
        return editResult;
    }

    @Cacheable(unless = "#result == null")
    public List<SystemDictVo> getAll() {
        SystemDict systemDict = new SystemDict();
        return systemDictService.list(systemDict);
    }

    @Cacheable(unless = "#result == null")
    public SystemDictVo getByKey(String key) {
        List<SystemDictVo> dicts = systemDictBiz.getAll();
        if (!ObjectUtils.isEmpty(dicts)) {
            for (SystemDictVo dict : dicts) {
                if (key.equals(dict.getDictName())) {
                    return dict;
                }
            }
        }
        return null;
    }

    @Cacheable(unless = "#result == null")
    public String getStringByKey(String key) {
        List<SystemDictVo> dicts = systemDictBiz.getAll();
        if (!ObjectUtils.isEmpty(dicts) && dicts.size() > 0) {
            for (SystemDictVo dict : dicts) {
                if (key.equals(dict.getDictName())) {
                    if (Constants.app_member_invitation.equals(key)) {
                        String value = dict.getDictValue();
                        JsonArray array = GsonUtils.fromJson(value, JsonArray.class);
                        JsonObject o = array.get(0).getAsJsonObject();
                        if (o.get("state").getAsInt() == 0) {
                            return new JsonArray().toString();
                        }
                    }
                    return dict.getDictValue();
                }
            }
        }
        return null;
    }

    public Object getOpenKey(String key) {
        if (getAllowKeySet().contains(key)) {
            SystemDictVo systemDictVo = systemDictBiz.getByKey(key);
            return systemDictVo == null ? "" : systemDictVo.getDictValue();
        }
        return "key不存在或者不在可查询范围内";
    }

    private List<String> getAllowKeySet() {
        List<String> strings = new ArrayList<>();
        try {
            SystemDictVo systemDictVo = systemDictBiz.getByKey(OPENABLE_SYSTEM_DIC_KEY);
            if (systemDictVo == null) {
                return strings;
            }
            String dictValue = systemDictVo.getDictValue();
            strings = JSONUtil.toList(JSONUtil.parseArray(dictValue), String.class);
        } catch (Exception e) {
            log.error("解析字典错误：{}", e);
            return new ArrayList<>();
        }
        return strings;
    }
}
